<template>
    <div class="app-container">
        <h2 style="display: flex">流程管理</h2>
        <div style="display: flex">
            <el-button icon="el-icon-edit" type="primary" size="small" @click="toDesign">在线设计流程</el-button>
            <el-button icon="el-icon-upload" type="primary" size="small" @click="handleClick">部署流程文件</el-button>
        </div>
        <el-alert style="margin:10px 0" title="说明：标识Key相同时，只显示最新版本流程。流程Key请保持和业务路由名保持一致。当前开通的工单申请流程key有 请假流程leave_key、备用金申请流程loan_key、git仓库申请流程dev_key" type="info" show-icon :closable="false" />

        <el-dialog title="部署流程文件" :visible.sync="dialogFormVisible" width="400px">
            <el-upload  accept="application/zip,application/xml,.bpmn"
                        :http-request="deployProcessFile" drag action="" :show-file-list="false">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text"><em>点击上传，选择BPMN流程文件</em></div>
                <div class="el-upload__text">仅支持 .zip、bpmn 格式文件</div>
            </el-upload>
        </el-dialog>

        <el-dialog title="流程图展示" :visible.sync="pngDialogVisible" align="center" width="70%" >
            <el-image :src="url" >
                <div slot="placeholder">流程图加载中 <i class="el-icon-loading"></i></div>
            </el-image>
        </el-dialog>

        <br>

        <el-table :data="list" stripe border style="width: 100%">
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column align="center" prop="name" label="流程名称" min-width="120"></el-table-column>
            <el-table-column  align="center" prop="key" label="标识Key" min-width="120"></el-table-column>
            <el-table-column  align="center" prop="state" label="状态" width="90" >
                <template slot-scope="{row}">
                    <!-- 流程定义状态，已启动、已暂停 -->
                    <el-tag :type="row.state == '已启动' ? 'success': 'danger'">{{row.state}}</el-tag>
                </template>
            </el-table-column>
<!--            <el-table-column  align="center" prop="xmlName" label="流程XML" min-width="160" >
                <template slot-scope="{row}">
                    &lt;!&ndash; 注意组件上使用原生事件，要加 .active &ndash;&gt;
                    <el-link type="primary" @click.native="clickExportXML(row.id)">{{row.xmlName}}</el-link>
                </template>
            </el-table-column>-->
            <el-table-column  align="center" prop="pngName" label="流程图片" min-width="160" >
                <template slot-scope="{row}">
                    <el-link type="primary" @click="clickPreviewImg(row.id)">{{row.pngName}}</el-link>
                </template>
            </el-table-column>
            <el-table-column  align="center" prop="version" label="版本号" width="90" >
                <template slot-scope="{row}"> v{{row.version}}.0</template>
            </el-table-column>
            <el-table-column  align="center" prop="deploymentTime" label="部署日期" width="160"></el-table-column>
            <el-table-column  align="center" label="操作" fixed="right" width="200">
                <template slot-scope="{row}">
                    <el-popconfirm :title="row.state === '已启动' ?
                        `暂停后，此流程下的所有任务都不允许往后流转，您确定暂停【${row.name || row.key}】吗？`:
                        `启动后，此流程下的所有任务都允许往后流转，您确定启动【${row.name || row.key}】吗？`"
                                   @confirm="updateState(row.id)" >
                        <el-button v-if="row.state === '已启动'" slot="reference" type="warning" size="mini">暂停</el-button>
                        <el-button v-else slot="reference" type="primary" size="mini">启动</el-button>
                    </el-popconfirm>
                    &nbsp;
                    <!-- 注意：当前element版本使用confirm事件无效，使用onConfirm才有效 -->
                    <el-popconfirm :title="`您确定删除【${row.name || row.key}】吗？`" @confirm="clickDelete(row)" >
                        <el-button slot="reference" type="danger" size="mini">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <div class="block" style="margin-top: 10px">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>


    </div>
</template>

<script>
export default {
    name: "ProcessDefinition",
    mounted() {
        this.getData();
    },
    data(){
        return {
            url: null, // 流程图
            key: null, // 流程key
            pngDialogVisible: false,
            dialogFormVisible: false,
            form: {},
            departments: [],
            roles: [],
            list: [],  //表格数据
            currentPage: 1,  //当前页
            pageSize: 10,  //单页记录条数
            total:0, //总记录条数
            file:[]
        }
    },
    methods:{
        getData(){
            let vm = this;
            this.axios({
                url: '/myapi/process/list/'+vm.currentPage+'/'+vm.pageSize,
                method: 'get'
            }).then(function (response) {
                if(response.data.code===200){
                    console.log(response.data);
                    vm.list = response.data.data.tableData;
                    vm.total = response.data.data.total;
                }
                else if(response.data.code===2001){
                    vm.$message.error('你还未登录!');
                    //路由回管理员后台登录页面
                    vm.$router.push("/adminLogin")
                }
                else if(response.data.code===4001){
                    vm.$message.error('无权限!');
                    //路由回管理员后台登录页面
                    vm.$router.push("/adminLogin")
                }
            });

            this.axios({
                url: '/myapi/department',
                method: 'get'
            }).then(function (response) {
                if(response.data.code===200){
                    console.log(response.data);
                    vm.departments = response.data.data.departments;
                }
                else if(response.data.code===2001){
                    vm.$message.error('你还未登录!');
                    //路由回管理员后台登录页面
                    vm.$router.push("/adminLogin")
                }
            });

            this.axios({
                url: '/myapi/role',
                method: 'get'
            }).then(function (response) {
                if(response.data.code===200){
                    console.log(response.data);
                    vm.roles = response.data.data.roles;
                }
                else if(response.data.code===2001){
                    vm.$message.error('你还未登录!');
                    //路由回管理员后台登录页面
                    vm.$router.push("/adminLogin")
                }
            });
        },
        modifyInfo(){
            let vm = this;
            this.axios({
                url: '/myapi/user/update',
                method: 'post',
                //使用data是body传参，使用params是query传参
                data:{
                    id: vm.form.id,
                    username: vm.form.username,
                    realName: vm.form.realName,
                    mail: vm.form.mail,
                    department: vm.form.department,
                    role: vm.form.role,
                    status: vm.form.status,
                    createDate: vm.form.createDate
                }
            }).then(function (response) {
                if(response.data.code===200){
                    vm.dialogFormVisible = false;
                    vm.getData();
                    vm.$message.success("修改成功");
                }
                else if(response.data.code===2001){
                    vm.$message.error('你还未登录!');
                    //路由回管理员后台登录页面
                    vm.$router.push("/adminLogin")
                }
                else if(response.data.code===4001){
                    vm.$message.error('无权限!');
                    //路由回管理员后台登录页面
                    vm.$router.push("/adminLogin")
                }
            });
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            console.log(this.pageSize);
            this.getData();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val;
            console.log(this.currentPage);
            this.getData();
        },
        sendMail(row) {
            let vm = this;
            this.axios({
                url: '/myapi/reset/password',
                method: 'post',
                //使用data是body传参，使用params是query传参
                data:{
                    id: row.id,
                    username: row.username,
                    realName: row.realName,
                    mail: row.mail,
                    department: row.department,
                    role: row.role,
                    status: row.status,
                    createDate: row.createDate
                }
            }).then(function (response) {
                console.log(response.data);
                if(response.data.code===200){
                    vm.$message({
                        duration:600,
                        message: '重置密码成功!',
                        type: 'success'
                    });
                }
            });
        },
        addFile(){
            //手动提交
            //this.$refs.upload.submit();
            let vm = this;
            let upData = new FormData();
            this.$refs.upload.submit();// 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
            this.file.forEach(function (file) {// 因为要上传多个文件，所以需要遍历
                upData.append('file', file, file.name);
            })
            vm.$axios.post('/myapi/importData',upData)
                    .then((response) => {
                        if (response.data.code===200) {
                            vm.$message.success('导入成功!');
                            vm.getData();
                        } else {
                            vm.$message.error('导入失败,请检查excel中的内容格式!');
                            vm.getData();
                        }
                    })
        },
        handleUploadForm(param) {
            this.file.push(param.file);
            /*            let thisInfo = this
                        let formData = new FormData()
                        // 在formData中加入我们需要的参数
                        formData.append('files', param.file)
                        formData.append('date', this.form.date)
                        formData.append('bdid', this.form.ins_id)
                        formData.append('uid', this.$store.state.id)
                        formData.append('textarea', this.form.textarea)
                        // 向后端发送数据
                        thisInfo.$axios.post('/myapi/user/claim/addClaim', formData).then((res) => {
                            if (res.data.success === true) {
                                thisInfo.$message.success('申请成功');
                                //thisInfo.open = false;
                                //thisInfo.getFileList();
                            } else {
                                thisInfo.$message.success('申请失败')
                            }
                        })*/
        },
        beforeUploadHandle(file) {
            // 以检查文件是否为.xlsx为例
            const fileName = file.name;
            const fileType = fileName.substring(fileName.lastIndexOf('.'));
            if (fileType === ".xlsx" || fileType === ".xls") {
                return true;
            }
            this.$message.error("只支持上传excel!");
            return false;
        },
        toDesign(){
            window.open("http://119.29.54.117:9013/");
        },
        handleClick(){
            this.dialogFormVisible = true;
        },
        // 部署流程文件
        async deployProcessFile(file) {
            // 封装上传图片的表单对象
            const data = new FormData();
            data.append('file', file.file);

            let vm = this;
            this.axios({
                url: '/myapi/process/file/deploy',
                method: 'post',
                data
            }).then(function (response) {
                if (response.data.code === 200) {
                    vm.$message.success('部署成功');
                    vm.getData();
                    vm.dialogFormVisible = false;
                }
                else {
                    vm.$message.error('部署失败');
                    vm.getData();
                    vm.dialogFormVisible = false;
                }
            })
        },
        // 预览图片
        clickPreviewImg(id) {
            // this.id = id
            let vm = this;
            vm.url = '/myapi/process/export/png/'+id
            vm.pngDialogVisible = true
        },
        // 导出xml流程文件
        clickExportXML(id) {
            let vm = this;
            this.axios({
                url: '/myapi/process/export/xml/'+id,
                method: 'get'
            }).then(function (response) {

            });
        },
        // 挂起或激活流程定义
        updateState(definitionId) {
            let vm = this;
            this.axios({
                url: '/myapi/process/state/'+definitionId,
                method: 'put'
            }).then(function (response) {
                if(response.data.code===200){
                    vm.$message.success('操作成功')
                    vm.getData()
                }
            });
        },
        // 删除该版本流程定义（当前没有流程实例正在执行）
        clickDelete(row) {
            // 发送删除请求
            let vm = this;
            this.axios({
                url: '/myapi/process/'+row.deploymentId+'/'+row.key,
                method: 'delete',
            }).then(function (response) {
                if(response.data.code===200){
                    vm.$message.success('删除成功')
                    vm.getData()
                }
            });
        },
    }
}
</script>

<style scoped>

</style>
